package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.WorkLog;
import com.joint.core.service.WorkLogService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/21.
 */
@ParentPackage("manage")
public class AjaxWorklogAction extends BaseFlowAction {
    @Resource
    private UsersService usersService;
    @Resource
    private WorkLogService workLogService;

    /**
     * 日志时间
     */
    private String logDate;
    /**
     * 日志内容
     */
    private String content;
    /**
     * 日志名称
     */
    private String name;
    /**
     * 附件
     */
    private String fileId;
    private String fileIds;

    private Users loginUser;
    private WorkLog workLog;
    private String viewtype;
    public String execute(){
        return "workLog";
    }

    public String list(){
        pager = new Pager(0);
        /*
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();

       // params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //个人
                params.put("creater",user);
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running,FlowEnum.ProcessState.Finished});
                pager=workLogService.findByPagerAndLimit(false, "worklog", pager, params);
            }else{
                //全部
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running,FlowEnum.ProcessState.Finished});
                pager=workLogService.findByPagerAndLimit(false,"worklog", pager, params);
            }
        }

        List<WorkLog> wlList;
        if (pager.getTotalCount() > 0){
            wlList = (List<WorkLog>) pager.getList();
        }else{
            wlList= new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(WorkLog workLog: wlList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",workLog.getId());
            rMap.put("year",workLog.getYear());
            rMap.put("month",workLog.getMonth());
            rMap.put("name",workLog.getName());
            rMap.put("creater", workLog.getCreater() != null ? workLog.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(workLog.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("state",workLog.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            fileId ="";
            workLog = workLogService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            flowNumStatus = workflowService.getFlowNumStatus(keyId);
            if(workLog.getFile() != null && workLog.getFile().size()>0){
                for(FileManage f:workLog.getFile()){
                    fileId+=f.getId()+",";
                }
            }

        }
        return "read";
    }

    public String input(){
        if (StringUtils.isNotEmpty(keyId)){
            fileId ="";
            workLog = workLogService.get(keyId);
            if(workLog.getFile() != null && workLog.getFile().size()>0){
                for(FileManage f:workLog.getFile()){
                    fileId+=f.getId()+",";
                }
            }
        }
        return "input";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            workLog=workLogService.get(keyId);
        }else{
            workLog=new WorkLog();
            workLog.setCreater(usersService.getLoginInfo());
        }
        Date date=DataUtil.StringToDate(logDate);
        String year=new SimpleDateFormat("yyyy").format(date);
        String month=new SimpleDateFormat("MM").format(date);
        workLog.setYear(year);
        workLog.setMonth(month);
        workLog.setName(name);
        workLog.setContent(content);
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManageService.get(f.trim()));
            }
        }
        workLog.setLogDate(date);
        workLog.setFile(fileManageList);
        workLog.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                workLogService.update(workLog);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                workLogService.save(workLog, "worklog", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                workLogService.approve(workLog, FlowEnum.ProcessState.Finished, var2, curDutyId, comment);
            } else {
                keyId = workLogService.commit(workLog, FlowEnum.ProcessState.Finished,"worklog", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String getLogDate() {
        return logDate;
    }

    public void setLogDate(String logDate) {
        this.logDate = logDate;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public WorkLog getWorkLog() {
        return workLog;
    }

    public void setWorkLog(WorkLog workLog) {
        this.workLog = workLog;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }
}
